package com.example.oauth2demo.web;

import com.example.oauth2demo.config.GiteeOauthConfig;
import com.example.oauth2demo.gitee.GiteeAccessToken;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author karidyang
 * @since 1.0.0
 * Date: 2021-04-19
 **/
@Controller
public class AuthController {
    private final static String AUTH_URL = "https://gitee.com/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code";
    @Autowired
    private GiteeOauthConfig giteeOauthConfig;

    @PostMapping("/login")
    public String login() {
        final String url = String.format(AUTH_URL, giteeOauthConfig.getClientId(), giteeOauthConfig.getRedirectUri());
        return "redirect:" + url;
    }

    @GetMapping("/login_back")
    public String loginBack(HttpSession session, String code, @RequestParam(required = false) String state) throws JsonProcessingException {
        //获取accessToken
        String accessToken = getAccessToken(code);
        System.out.println(accessToken);
        Map<String, Object> user = getUser(accessToken);

        session.setAttribute("token", accessToken);
        session.setAttribute("user", user.get("name"));
        session.setAttribute("avatar_url", user.get("avatar_url"));

        return "redirect:/";

    }

    @GetMapping("/login2")
    public String login2()  {
        System.out.println("login2.......");

        return "login2";
    }

    private Map<String, Object> getUser(String accessToken) throws JsonProcessingException {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://gitee.com/api/v5/user?access_token=" + accessToken;

        final ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
        String json = entity.getBody();
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(json, Map.class);
    }

    @PostMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("token");
        return "redirect:/";
    }

    private String getAccessToken(String code) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code";
        Map<String, String> urlVariables = new HashMap<>(4);
        urlVariables.put("code", code);
        urlVariables.put("client_id", giteeOauthConfig.getClientId());
        urlVariables.put("redirect_uri", giteeOauthConfig.getRedirectUri());
        urlVariables.put("client_secret", giteeOauthConfig.getClientSecret());

        final ResponseEntity<GiteeAccessToken> entity = restTemplate.postForEntity(url, urlVariables, GiteeAccessToken.class);
        return Objects.requireNonNull(entity.getBody()).getAccess_token();
    }
}
